const db = require('../db')
const bcrypt = require('bcryptjs')
const jwt = require('jsonwebtoken')
const { log } = require('console')
const db_execute = async (sql, params) => {
    if (!params) {
        return db.execute(sql, params); // 没有参数直接执行
    } else {
        const new_params = params.map(item => {
            if (typeof item === 'number') {
                return item.toString();  // 如果是数字，转换成字符串
            }
            return item;
        });
        return db.execute(sql, new_params); // 执行查询并传递转换后的参数
    }
}

class Account {
    static async addAccount(accountData) {
        try {
            const { employee_id, username, password, email, role } = accountData

            const hashPassword = await bcrypt.hash(password, 10)
            const query = `INSERT INTO employee_accounts (employee_id, username, password, email, role, created_at, updated_at) VALUES (?, ?, ?, ?, ?, NOW(), NOW())`

            const result = await db_execute(query, [employee_id, username, hashPassword, email, role])

            return result[0].affectedRows
        } catch (error) {
            throw new Error('添加账户失败: ' + error.message)
        }

    }

    static async getAccount(accountData) {
        try {
            const { username, password } = accountData //获取传过来的用户名和密码
            const query = `SELECT * FROM employee_accounts WHERE username = ?`  //定义查询语句
            const [rows] = await db_execute(query, [username]) //查询数据表有无该用户名对应的用户
            if (rows.length === 0) {
                return null
            }

            const account = rows[0]  //保存该用户的信息
            const passwordMatch = await bcrypt.compare(password, account.password) //再验证密码是否匹配 
            //(这里使用的bcrypt是一个加密解密的依赖)
            if (!passwordMatch) {
                return null
            }

            //生成token
            const token = jwt.sign({ username: account.username, employee_id: account.employee_id },
                //（这里使用的jwt.sign是用来生成token的依赖 格式为 jwt.sign({用户信息},密钥,有效期限) ）
                process.env.JWT_SECRET,
                { expiresIn: "1h" }
            )

            return {
                token,
                account
            }

        } catch (error) {
            throw new Error('获取账户失败: ' + error.message)
        }

    }

    static async updateAccount(accountData) {
        try {
            const { username, password } = accountData

            const query = `SELECT * FROM employee_accounts WHERE username = ?`
            const account = await db_execute(query, [username])

            if (account.length === 0) {
                return null
            }
            const hashPassword = await bcrypt.hash(password, 10)
            const updateQuery = `UPDATE employee_accounts SET password = ? WHERE username = ?`
            const result = await db_execute(updateQuery, [hashPassword, username])
            return result[0].affectedRows
        } catch (error) {
            throw new Error('更新账户失败: ' + error.message)
        }
    }
}

module.exports = Account